package com.hzit.sb2.controller;

import com.hzit.sb2.bean.Emp;
import com.hzit.sb2.service.IDeptService;
import com.hzit.sb2.service.IEmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;



@Controller
@RequestMapping("/emp")
public class EmpController {
    @Autowired
    IEmpService empService;
    @Autowired
    IDeptService deptService;

    /**
     * 员工list分页
     * @param model
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping("/main")
    public String toMain(Model model,
                         @RequestParam(value = "deptno",required = false)Integer deptno,
                         @RequestParam(value = "ename",required = false)String ename,
                         @RequestParam(value = "page",defaultValue = "1")Integer page,
                         @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize){
        ename=ename==""?null:ename;
        model.addAttribute("deptList",deptService.findAll());
        model.addAttribute("pageInfo",empService.findAll(deptno,ename,page,pageSize));
        return "main";
    }

    /**
     * 跳转添加页面
     * @param model
     * @return
     */
    @GetMapping("/add")
    public String toAdd(Model model){
        model.addAttribute("deptList",deptService.findAll());
        return "addEmp";
    }

    /**
     * 添加员工
     * @param emp
     * @return
     */
    @RequestMapping("/add")
    public String addEmp(Emp emp){
        empService.insert(emp);
        return "redirect:/emp/main";
    }

    /**
     * 删除单个员工
     * @param empno
     * @return
     */
    @DeleteMapping("/{empno}")
    public String delEmp(@PathVariable("empno")Integer empno){
        empService.deleteByPrimaryKey(empno);
        return "redirect:/emp/main";
    }

    /**
     * 跳转edit页面
     * @param model
     * @param empno
     * @return
     */
    @GetMapping("/edit/{empno}")
    public String toEdit(Model model,@PathVariable("empno")Integer empno){
        model.addAttribute("deptList",deptService.findAll());
        model.addAttribute("emp",empService.selectByPrimaryKey(empno));
        return "editEmp";
    }

    /**
     * 修改数据
     * @param emp
     * @return
     */
    @PutMapping("/edit")
    public String edit(Emp emp){
        empService.updateEmp(emp);
        return "redirect:/emp/main";
    }

    /**
     * 批量删除
     * @param emps
     * @return
     */
    @DeleteMapping("/delSelected")
    public String delSelected(Integer[] emps){
        for (Integer empno : emps) {
            empService.deleteByPrimaryKey(empno);
        }
        return "redirect:/emp/main";
    }

}
